package com.pengbei.enshrine.ui.login;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;

import com.google.gson.Gson;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.OnDownloadListener;
import com.hjq.http.model.FileContentResolver;
import com.hjq.http.model.HttpMethod;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.pengbei.enshrine.R;
import com.pengbei.enshrine.base.BaseActivity;
import com.pengbei.enshrine.common.dialog.AgreementDialog;
import com.pengbei.enshrine.common.dialog.AgreementSureDialog;
import com.pengbei.enshrine.common.dialog.callback.AppUpdateCallBack;
import com.pengbei.enshrine.common.dialog.callback.PermissionIntroduceCallBack;
import com.pengbei.enshrine.common.utils.CheckUtils;
import com.pengbei.enshrine.common.utils.CommonUtils;
import com.pengbei.enshrine.common.utils.DialogUtils;
import com.pengbei.enshrine.common.utils.PreferencesUtils;
import com.pengbei.enshrine.common.utils.StatusBarUtils;
import com.pengbei.enshrine.common.utils.ToastUtils;
import com.pengbei.enshrine.common.view.DownLoadProgressBar;
import com.pengbei.enshrine.network.bean.PermissionIntroduceModel;
import com.pengbei.enshrine.ui.main.MainActivity;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class SplashActivity extends BaseActivity {
    private String showwelecom = "";
    private String protocolprompt = "";

    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
    Date curDate = new Date(System.currentTimeMillis());//获取当前时间
    String str = formatter.format(curDate);
    /**
     * 下载apk
     */
    private String UPDATE_SERVERAPK = str + "喜得收藏.apk";



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtils.StatusBarTransparentBgBlackText(SplashActivity.this);
        showwelecom = PreferencesUtils.getString(SplashActivity.this,"showwelecom", "");
        protocolprompt = PreferencesUtils.getString(SplashActivity.this,"promptagree", "");
        showAgreement();
    }

    /**
     * 先显示协议弹窗
     */
    private void showAgreement() {
        if (!TextUtils.isEmpty(protocolprompt)) {
            initThirdSDK();
        } else {
            DialogUtils.showAgreementDialog(SplashActivity.this, new AgreementDialog.AgreementCallBack() {
                @Override
                public void Agree() {
                    PreferencesUtils.putString(SplashActivity.this, "promptagree", "agree");
                    initThirdSDK();
                }

                @Override
                public void Cancal() {
                    DialogUtils.showAgreementSureDialog(SplashActivity.this, new AgreementSureDialog.AgreementSureCallBack() {
                        @Override
                        public void Agree() {
                            initThirdSDK();
                        }

                        @Override
                        public void ExitApp() {
                            finish();
                        }

                        @Override
                        public void Again() {
                            showAgreement();
                        }

                        @Override
                        public void BasicMode() {
                            goactivity(true);
                        }
                    });
                }
            });
        }
    }

    /**
     * 需要在同意隐私之后才可以开始初始化第三方SDK和请求等
     * */
    private void initThirdSDK(){

        checkAppVersion();
    }

    String updateType = "0";
    /**
     * 检查更新
     */
    private void checkAppVersion() {
        String updatetext = "";
        List<String> updatemsg = new ArrayList<String>();
        updatemsg.add("解决了BUG");
        updatemsg.add("修改了页面");
        switch (updateType) {
            case "0"://不需要更新
                goactivity(false);
                break;
            case "1"://强制更新
                updatetext = getString(R.string.lc_common_13);
                showUpdate(updatemsg, updatetext, "https://dldir1.qq.com/weixin/android/weixin8015android2020_arm64.apk", false);
                break;
            case "2"://非强制更新
                updatetext = getString(R.string.lc_common_14);
                showUpdate(updatemsg, updatetext, "https://dldir1.qq.com/weixin/android/weixin8015android2020_arm64.apk", true);
                break;
        }
    }

    /**
     * 需要更新
     */
    private void showUpdate(List<String> updatemsg, String updateText, String apkurl, boolean canNext) {
        DialogUtils.showAppUpdateDialog(SplashActivity.this, updatemsg, updateText, new AppUpdateCallBack() {
            @Override
            public void Update(DownLoadProgressBar progressBar) {
                if (!TextUtils.isEmpty(apkurl)) {
                    ToastUtils.showError("下载链接不存在");
                    return;
                }
                downloadApk(apkurl, progressBar);
            }

            @Override
            public void Cancal() {
                if (canNext) {
                    goactivity(false);
                }
            }
        });
    }

    /**
     * 下载安装包
     */
    private void downloadApk(String apkurl, DownLoadProgressBar progressBar) {
        // 如果是放到外部存储的应用专属目录则不需要适配分区存储特性
        File file = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), UPDATE_SERVERAPK);
        EasyHttp.download(this)
                .method(HttpMethod.GET)
                .file(file)
                .url(apkurl)
                // 设置断点续传（默认不开启）
                .resumableTransfer(true)
                .listener(new OnDownloadListener() {
                    @Override
                    public void onDownloadStart(File file) {
                        progressBar.setProgress(0);
                    }

//                    @Override
//                    public void onDownloadByteChange(File file, long totalByte, long downloadByte) {
//                        int fileSize = (int) totalByte; //获取文件大小并将其转换为整数
//                        int downsize = (int) downloadByte;//获取下载大小并将其转换为整数
//                        progressBar.setMax(fileSize);
//                        progressBar.setProgress(downsize);
//                    }

                    @Override
                    public void onDownloadProgressChange(File file, int progress) {
                        progressBar.setProgress(progress);
                    }

                    @Override
                    public void onDownloadSuccess(File file) {
                        ToastUtils.showSuccess("下载成功：" + file.getPath());
                        showPermissionDialog(SplashActivity.this, file);
                    }

                    @Override
                    public void onDownloadFail(File file, Throwable throwable) {
                        ToastUtils.showSuccess("下载失败：" + file.getPath());
                        file.delete();
                    }

                    @Override
                    public void onDownloadEnd(File file) {

                    }
                })
                .start();
    }



    /**
     * 目标页面
     */
    private void goactivity(boolean goBasicMode) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (goBasicMode) {//基本模式

                } else {
                    if (TextUtils.isEmpty(showwelecom)) {//欢迎页面
                        WelecomActivity.goToThisActivity(SplashActivity.this);
                        finish();
                    } else {//首页
                        MainActivity.goToThisActivity(SplashActivity.this);
                        finish();
                    }
                }
            }
        }, 1000);
    }


    /**
     * 判断权限
     */
    private void showPermissionDialog(Activity context, File file) {
        if (CheckUtils.checkPermission(context, CommonUtils.permission_install)) {
            List<PermissionIntroduceModel> permissionlist = new ArrayList<PermissionIntroduceModel>();
            PermissionIntroduceModel model2 = new PermissionIntroduceModel();
            model2.setName(getString(R.string.permission1));
            model2.setContent(getString(R.string.permission2));
            permissionlist.add(model2);
            DialogUtils.showPermissionIntroduceDialog(context, permissionlist, new PermissionIntroduceCallBack() {
                @Override
                public void Sure() {
                    getPermission(context, file);
                }

                @Override
                public void Cancal() {
                    ToastUtils.showError(context.getString(R.string.lc_common_12));
                }
            });
        } else {
            installApk(context, file);
        }
    }

    private void getPermission(Activity context, File file) {
        XXPermissions
                .with(context)
                .permission(Permission.REQUEST_INSTALL_PACKAGES)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                        if (allGranted) {
                            installApk(context, file);
                        } else {
                            ToastUtils.showError(context.getString(R.string.lc_common_12));
                        }
                    }

                    @Override
                    public void onDenied(@NonNull List<String> permissions, boolean doNotAskAgain) {
                        ToastUtils.showError(context.getString(R.string.lc_common_12));
                    }
                });
    }

    /**
     * 安装应用
     */
    public void installApk(Activity context, File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            if (file instanceof FileContentResolver) {
                uri = ((FileContentResolver) file).getContentUri();
            } else {
                uri = FileProvider.getUriForFile(context, context.getPackageName() + ".provider", file);
            }
        } else {
            uri = Uri.fromFile(file);
        }
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        // 对目标应用临时授权该 Uri 读写权限
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        context.startActivity(intent);
    }


}

